<script setup>
import { computed, onMounted, ref } from 'vue'
import { useWardrobesStore } from '../stores/wardrobes'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

const store = useWardrobesStore()
const isDesktop = ref(false)
const tableHeight = ref(600)

const listedWardrobes = computed(() => 
  store.list.filter(w => w.status === 'listed')
)

const listedCount = computed(() => listedWardrobes.value.length)

const totalSaleValue = computed(() => 
  listedWardrobes.value.reduce((sum, w) => sum + (w.sale_price || 0), 0)
)

const averagePrice = computed(() => 
  listedCount.value > 0 ? totalSaleValue.value / listedCount.value : 0
)

const profitMargin = computed(() => {
  if (listedCount.value === 0) return 0
  const totalBuyValue = listedWardrobes.value.reduce((sum, w) => sum + (w.buy_price || 0), 0)
  const totalProfit = totalSaleValue.value - totalBuyValue
  return totalBuyValue > 0 ? (totalProfit / totalBuyValue) * 100 : 0
})

onMounted(() => {
  store.fetchList()
  detectDevice()
  window.addEventListener('resize', detectDevice)
})

function refreshList() {
  store.fetchList()
}

function detectDevice() {
  const userAgent = navigator.userAgent.toLowerCase()
  const isMobile = /mobile|android|iphone|ipad|phone/i.test(userAgent)
  const isTablet = /tablet|ipad/i.test(userAgent)
  const screenWidth = window.innerWidth
  
  isDesktop.value = !isMobile && !isTablet && screenWidth > 1024
  
  // 根据屏幕高度调整表格高度
  if (isDesktop.value) {
    tableHeight.value = window.innerHeight - 300
  } else {
    tableHeight.value = 600
  }
}

function getStatusType(status) {
  const statusMap = {
    'pending_disassembly': 'warning',
    'pending_listing': 'info',
    'listed': 'success',
    'pending_installation': 'primary',
    'pending_settlement': 'warning',
    'pending_archive': 'info',
    'archived': 'default'
  }
  return statusMap[status] || 'default'
}

function getStatusText(status) {
  const statusMap = {
    'pending_disassembly': '待拆',
    'pending_listing': '待上架',
    'listed': '已上架',
    'pending_installation': '待安装',
    'pending_settlement': '待结账',
    'pending_archive': '待存档',
    'archived': '已存档'
  }
  return statusMap[status] || status
}

function formatDate(date) {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

function viewDetail(id) {
  ElMessage.info(`查看衣柜 #${id} 的详细信息`)
  // 这里可以跳转到详情页或打开详情弹窗
}
</script>

<template>
  <div class="listed-container" :class="{ 'desktop': isDesktop }">
    <div class="page-header">
      <h1>🛒 已上架 - 销售中</h1>
      <p>查看所有已上架正在销售的衣柜列表</p>
    </div>

    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">已上架衣柜列表</span>
          <div class="header-actions">
            <el-button 
              type="primary" 
              @click="refreshList"
              :loading="store.loading"
              size="small"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-tag type="success" size="small">
              共 {{ listedCount }} 件
            </el-tag>
          </div>
        </div>
      </template>

      <div class="table-container">
        <el-table 
          :data="listedWardrobes" 
          style="width: 100%"
          :loading="store.loading"
          stripe
          border
          class="wardrobe-table"
          :max-height="tableHeight"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" fixed="left">
            <template #default="{ row }">
              <el-tag size="small" type="info">#{{ row.id }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="code" label="编号" width="120" fixed="left">
            <template #default="{ row }">
              <span class="code-text">{{ row.code }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="name" label="名称" min-width="150">
            <template #default="{ row }">
              <div class="name-cell">
                <span class="name-text">{{ row.name }}</span>
                <el-tag 
                  v-if="row.specs" 
                  size="small" 
                  type="warning"
                  class="specs-tag"
                >
                  {{ row.specs.length > 20 ? row.specs.substring(0, 20) + '...' : row.specs }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="sale_price" label="售价" width="120" align="center">
            <template #default="{ row }">
              <span class="price-text">¥{{ row.sale_price?.toFixed(2) || '0.00' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="buy_price" label="收购价" width="120" align="center">
            <template #default="{ row }">
              <span class="buy-price-text">¥{{ row.buy_price?.toFixed(2) || '0.00' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="description" label="描述" min-width="200">
            <template #default="{ row }">
              <div class="description-cell">
                <span v-if="row.description" class="description-text">
                  {{ row.description.length > 50 ? row.description.substring(0, 50) + '...' : row.description }}
                </span>
                <span v-else class="no-description">暂无描述</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag 
                :type="getStatusType(row.status)" 
                size="small"
                class="status-tag"
              >
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="创建时间" width="160" align="center">
            <template #default="{ row }">
              <span class="time-text">{{ formatDate(row.created_at) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small"
                @click="viewDetail(row.id)"
                class="action-btn"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="listedWardrobes.length === 0 && !store.loading" class="empty-state">
        <el-empty description="暂无已上架衣柜" />
      </div>
    </el-card>

    <!-- 桌面端统计卡片 -->
    <div v-if="isDesktop" class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">📦</div>
              <div class="stat-info">
                <div class="stat-number">{{ listedCount }}</div>
                <div class="stat-label">已上架</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">💰</div>
              <div class="stat-info">
                <div class="stat-number">¥{{ totalSaleValue.toFixed(2) }}</div>
                <div class="stat-label">总售价</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">📈</div>
              <div class="stat-info">
                <div class="stat-number">{{ averagePrice.toFixed(2) }}</div>
                <div class="stat-label">平均售价</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">🎯</div>
              <div class="stat-info">
                <div class="stat-number">{{ profitMargin.toFixed(1) }}%</div>
                <div class="stat-label">利润率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
.listed-container {
  max-width: 1400px;
  margin: 0 auto;
}

.listed-container.desktop {
  max-width: none;
  margin: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  color: white;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 2.5rem;
  font-weight: 700;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.page-header p {
  margin: 0;
  font-size: 1.1rem;
  opacity: 0.9;
}

.table-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
}

.desktop .table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.table-container {
  overflow-x: auto;
}

.desktop .table-container {
  flex: 1;
  overflow: auto;
}

.wardrobe-table {
  border-radius: 8px;
  overflow: hidden;
}

.code-text {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #409eff;
}

.name-cell {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.name-text {
  font-weight: 600;
  color: #303133;
}

.specs-tag {
  align-self: flex-start;
}

.price-text {
  font-weight: 700;
  color: #67c23a;
  font-size: 1.1rem;
}

.buy-price-text {
  font-weight: 600;
  color: #e6a23c;
}

.description-cell {
  max-width: 200px;
}

.description-text {
  color: #606266;
  line-height: 1.4;
}

.no-description {
  color: #c0c4cc;
  font-style: italic;
}

.status-tag {
  font-weight: 600;
}

.time-text {
  color: #909399;
  font-size: 0.9rem;
}

.action-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

/* 桌面端统计卡片 */
.stats-section {
  margin-top: 30px;
}

.desktop .stats-section {
  margin-top: 20px;
  flex-shrink: 0;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
}

.stat-icon {
  font-size: 2.5rem;
  opacity: 0.8;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 1.5rem;
  font-weight: 700;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .desktop .stats-section .el-col {
    width: 50%;
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .page-header h1 {
    font-size: 2rem;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .table-container {
    margin: 0 -10px;
  }
  
  .stats-section {
    display: none;
  }
}

@media (max-width: 480px) {
  .page-header h1 {
    font-size: 1.8rem;
  }
  
  .page-header p {
    font-size: 1rem;
  }
  
  .table-card {
    margin: 0 10px;
  }
  
  .wardrobe-table {
    font-size: 12px;
  }
}
</style>


